package com.biostime.terminal.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class XMLWriter extends XMLOutputter {
	private static XMLWriter instance = new XMLWriter();
	private static Log log = LogFactory.getLog(XMLWriter.class);

	private XMLWriter() {
		super();
		Format format = Format.getPrettyFormat();
        format.setEncoding("utf-8");//设置编码
        format.setIndent("  ");//设置缩进
        this.setFormat(format);
	}

	/**
	 * 把XML文档输出为byte数组。因为XML文档的输出涉及编码，所以不使用String输出。
	 * 
	 * @param doc XML文档
	 * @return byte数组
	 */
	public static byte[] writeByteArray(Document doc) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			instance.output(doc, bos);
			bos.close();
			return bos.toByteArray();
		} catch (IOException e) {
			log.error("", e);
			return new byte[0];
		}
	}

	/**
	 * 把XML元素输出为字符串。
	 * 
	 * @param e XML元素
	 * @return XML元素对应的字符串
	 */
	public static String writeString(Element e) {
		return instance.outputString(e);
	}
}
